/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.rainbowsheep.reisorg.rest.service.util;

import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.rainbowsheep.reisorg.rest.service.service.LanguageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.LocaleEditor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;

/**
 *
 * @author ieme
 */
public class LocaleHandler extends LocaleChangeInterceptor {

    @Autowired
    private LanguageService langService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws ServletException {

        String newLocale = request.getParameter("locale");
        LocaleEditor localeEditor = new LocaleEditor();
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if (localeResolver == null) {
            throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
        }
        if (newLocale != null) {
            if (langService.getLanguageByName(newLocale) == null) {
                throw new IllegalArgumentException("language not supported");
            }
            localeEditor.setAsText(newLocale);
            Localizer.setCurrentLanguage(langService.getLanguageByName(newLocale));
        } else {
            localeEditor.setAsText("nl");
            Localizer.setCurrentLanguage(langService.getLanguageByName("nl"));
        }

        localeResolver.setLocale(request, response, (Locale) localeEditor.getValue());
        return true;
    }

}
